package com.yunda.nebula.gateway.sync.nacos;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractSharedListener;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.yunda.nebula.gateway.core.enums.DataEventTypeEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhiguo.dong
 * @date 2020/9/23
 */
@Slf4j
public class AppIdRefreshListener extends AbstractSharedListener {
    private NacosSyncDataService nacosSyncDataService;

    public AppIdRefreshListener (NacosSyncDataService nacosSyncDataService) {
        this.nacosSyncDataService = nacosSyncDataService;
    }

    @Override
    public void innerReceive(String dataId, String group, String configInfo) {

        Map<String, Listener> listenerMap = nacosSyncDataService.getListenerMap();

        try {
            List<String> list = JSONObject.parseArray(configInfo,String.class);
            //appid increment
            list.forEach(appid->{
                if (!listenerMap.containsKey(appid)){
                    nacosSyncDataService.doFetchAppConfig(appid,DataEventTypeEnum.CREATE);

                }
            });

            //appid reduce
            listenerMap.keySet().forEach(appid->{
                if (NacosSyncDataService.APPID.equals(appid)){
                    return;
                }
                if (!list.contains(appid)){
                    nacosSyncDataService.doRemoveAppConfig(appid, DataEventTypeEnum.DELETE);

                }

            });



        } catch (Exception e) {
            log.error(" nacos refresh failed",e);
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (Exception ex) {
                // ignore
            }
            innerReceive(dataId, group, configInfo);
        }

    }
}
